package com.plcoding.room

import com.plcoding.data.MessageDataSource
import com.plcoding.data.model.Message
import io.ktor.http.cio.websocket.*
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.util.concurrent.ConcurrentHashMap

class RoomController(
    private val messageDataSource: MessageDataSource
) {
    private val members: ConcurrentHashMap<String, Member> = ConcurrentHashMap<String, Member>();

    fun onJoin(
        userName: String,
        sessionID: String,
        socket: WebSocketSession
    ){
        if(members.containsKey(userName)){
            throw MemberAlreadyExistsException()
        }

        members[userName] = Member(
            username = userName,
            sessionId = sessionID,
            socket = socket
        )
    }
    suspend fun sendMessage(sendUsername: String, message: String){
        val messageEntity = Message(
            text = message,
            username = sendUsername,
            timestamp = System.currentTimeMillis()
        )
        members.values.forEach{member ->
            val messageStr = Json.encodeToString(messageEntity);
            member.socket.send(Frame.Text(messageStr))
        }
        messageDataSource.insertMessage(messageEntity);
    }

    suspend fun getAllMessage():List<Message>{
        return messageDataSource.getAllMessages();
    }

    suspend fun tryDisconnect(username: String){
        members[username]?.socket?.close();
        if(members.containsKey(username)){
            members.remove(username)
        }

    }

}